# -*- coding: utf-8 -*-
import sys
import os
import PySide2
import webbrowser
from PySide2.QtCore import QCoreApplication, Signal, Qt, QSize, QThread
from PySide2.QtWidgets import (
    QApplication, QMainWindow, QFileDialog, QTableWidgetItem, QSpinBox, 
    QMessageBox, QHeaderView, QMenu, QAction, QInputDialog, QComboBox,
)
from PySide2.QtGui import QCursor, QIcon
#导入designer工具生成的模块
from design.ui import Ui_MainWindow

from functional.utils import (
        FunctionalThread, collect_transfer_addr, 
        collect_statistic_item, collect_count_addr,
        SPLIT_FUNC_DICT, JOIN_STR_DICT, file_path_add_sub,
        AddrTableMenu, StatisticTableMenu
)
from functional.bind_fullname import bind_fullname_func
from functional.first_author import first_author_func
from functional.filter import filter_func
from functional.translate import translate_func
from functional.count import count_func
from functional.bind_dept import bind_name_dept
#from qt_material import apply_stylesheet

class MyMainUi(QMainWindow, Ui_MainWindow):
    signal_first = Signal(str)
    signal_filter = Signal(str)
    signal_translate = Signal(str)
    signal_count = Signal(str)
    signal_bind_fullname = Signal(str)
    signal_bind_dept = Signal(str)

    def __init__(self, parent):
        self.parent = parent
        super(MyMainUi, self).__init__(parent)
        self.setupUi(parent)
        self.init_connect()
        self.init_table()
        self.init_ico()
        self.init_config()

    def init_connect(self):
        self.tb_input.clicked.connect(self.on_tb_input_clicked)
        self.tb_output.clicked.connect(self.on_tb_output_clicked)

        self.tb_filter_lib.clicked.connect(self.on_tb_filter_lib_clicked)

        self.tb_translate_lib.clicked.connect(self.on_tb_translate_lib_clicked)

        self.btn_input_dept.clicked.connect(self.on_btn_input_dept_clicked)

        self.action_repo.triggered.connect(self.on_action_repo)

        self.btn_bind_fullname.clicked.connect(self.on_btn_bind_fullname_clicked)
        self.btn_first.clicked.connect(self.on_btn_first_clicked)
        self.btn_filter.clicked.connect(self.on_btn_filter_clicked)
        self.btn_translate.clicked.connect(self.on_btn_translate_clicked)
        self.btn_count.clicked.connect(self.on_btn_count_clicked)
        self.btn_name_dept.clicked.connect(self.on_btn_bind_name_dept_clicked)

        self.signal_first.connect(self.on_signal_first)
        self.signal_filter.connect(self.on_signal_filter)
        self.signal_translate.connect(self.on_signal_translate)
        self.signal_count.connect(self.on_signal_count)
        self.signal_bind_fullname.connect(self.on_signal_bind_fullname)
        self.signal_bind_dept.connect(self.on_signal_bind_dept)

        self.count_mode = "author"
        self.rb_count_author.clicked.connect(self.on_rb_count_author_clicked)
        self.rb_count_college.clicked.connect(self.on_rb_count_college_clicked)

        self.tab_functional.currentChanged.connect(self.on_tab_functional_current_changed)

    def init_table(self):
        self.tw_addr.horizontalHeader().setSectionResizeMode(2, QHeaderView.Stretch)
        self.tw_addr.setColumnWidth(1, 70)
        self.addr_menu = AddrTableMenu(self.tw_addr)

        self.tw_statistic.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        self.statistic_menu = StatisticTableMenu(self.tw_statistic)

    def init_ico(self):
        icon_dir = os.path.join(os.path.dirname(__file__), 'ico/woscopus.ico')
        icon = QIcon()
        icon.addFile(icon_dir, QSize(), QIcon.Normal, QIcon.Off)
        self.parent.setWindowIcon(icon)

    def init_config(self):
        self.default_file_dir = "."
        self.parent.showMaximized()

        self.bind_thread_name = "bind_thread"
        self.first_thread_name = "first_thread"
        self.filter_thread_name = "filter_thread"
        self.translate_thread_name = "translate_thread"
        self.count_thread_name = "count_thread"

        self.signal_of_thread = {
        	"bind_thread": self.signal_bind_fullname,
        	"first_thread": self.signal_first,
        	"filter_thread": self.signal_filter,
        	"translate_thread": self.signal_translate,
        	"count_thread": self.signal_count,
        }

    def update_default_file_dir(self, file_path):
        self.default_file_dir = os.path.dirname(file_path)

    def get_input_excel_file(self):
        file_path, _ = QFileDialog.getOpenFileName(self, "选择Excel文件", self.default_file_dir, "Excel文件 (*.xlsx *.xls *.xlsm *.xltx *.xltm)")

        if file_path:
            self.update_default_file_dir(file_path)

        # 避免模态窗口关闭导致的主窗口跑到其他窗口后的问题
        self.parent.activateWindow()

        return file_path

    def get_input_txt_file(self):
        file_path, _ = QFileDialog.getOpenFileName(self, "选择变体库文件", self.default_file_dir, "TXT文件 (*.txt)")

        if file_path:
            self.update_default_file_dir(file_path)

        # 避免模态窗口关闭导致的主窗口跑到其他窗口后的问题
        self.parent.activateWindow()

        return file_path

    def get_output_excel_file(self):
        file_path, _ = QFileDialog.getSaveFileName(self, "选择Excel文件", self.default_file_dir, "Excel文件 (*.xlsx *.xls)")

        if file_path:
            self.update_default_file_dir(file_path)

        # 避免模态窗口关闭导致的主窗口跑到其他窗口后的问题
        self.parent.activateWindow()

        return file_path

    # 输入设置文件名，并自动配置输出文件名
    def on_tb_input_clicked(self):
        file_path = self.get_input_excel_file()
        if file_path:
            self.pt_input.setPlainText(file_path)
            self.pt_output.setPlainText(file_path_add_sub(file_path, self.tab_functional.tabText(self.tab_functional.currentIndex())))

    # 设置输出文件名
    def on_tb_output_clicked(self):
        file_path = self.get_output_excel_file()
        if file_path:
            self.pt_output.setPlainText(file_path)

    # 设置变体库文件名
    def on_tb_filter_lib_clicked(self):
        file_path = self.get_input_txt_file()
        if file_path != "":
            self.pt_filter_lib.setPlainText(file_path)

    # 设置翻译地址库文件名
    def on_tb_translate_lib_clicked(self):
        file_path = self.get_input_excel_file()
        if file_path != "":
            self.pt_translate_lib.setPlainText(file_path)

    # 设置匹配部门映射文件名
    def on_btn_input_dept_clicked(self):
        file_path = self.get_input_excel_file()
        if file_path != "":
            self.input_dept_file.setPlainText(file_path)

    # 菜单栏获取源代码及文档地址
    def on_action_repo(self):
        webbrowser.open("https://gitee.com/leyouLIUQ/woscopus/tree/master")

    def thread_is_running(self, thread_name):
        # 有执行中的任务线程，弹出警告框，取消执行
        if hasattr(self, thread_name) and getattr(self, thread_name).isRunning():
            QMessageBox.warning(self, "警告", "任务进行中，请等待完成")
            return True
        else:
            return False

    # 获取第一作者
    def on_btn_bind_fullname_clicked(self):
        this_thread_name = self.bind_thread_name
        if self.thread_is_running(this_thread_name):
            return
        # 清除上次任务的记录
        self.txt_bind_fullname_state.setText("")
        # 加载线程
        setattr(self, this_thread_name, FunctionalThread(
            bind_fullname_func,
            self.pt_input.toPlainText(),
            self.pt_output.toPlainText(),
            self.pt_sheet.toPlainText(),
            self.sb_row_from.value(),
            self.sb_row_to.value(),
            collect_transfer_addr(self.tw_addr),
            self.sb_fullname_col.value(),
            self.signal_bind_fullname,
        ))
        # 启动线程
        this_thread = getattr(self, this_thread_name)
        this_thread.start(QThread.HighestPriority)

    # 获取第一作者
    def on_btn_first_clicked(self):
        this_thread_name = self.bind_thread_name
        if self.thread_is_running(this_thread_name):
            return
        # 清除上次任务的记录
        self.txt_first_state.setText("")
        # 加载线程
        setattr(self, this_thread_name, FunctionalThread(
            first_author_func,
            self.pt_input.toPlainText(),
            self.pt_output.toPlainText(),
            self.pt_sheet.toPlainText(),
            self.sb_row_from.value(),
            self.sb_row_to.value(),
            collect_transfer_addr(self.tw_addr),
            self.signal_first,
        ))
        # 启动线程
        this_thread = getattr(self, this_thread_name)
        this_thread.start(QThread.HighestPriority)

    def on_btn_filter_clicked(self):
        this_thread_name = self.bind_thread_name
        if self.thread_is_running(this_thread_name):
            return
        self.txt_filter_state.setText("")
        setattr(self, this_thread_name, FunctionalThread(
            filter_func,
            self.pt_input.toPlainText(),
            self.pt_output.toPlainText(),
            self.pt_sheet.toPlainText(),
            self.sb_row_from.value(),
            self.sb_row_to.value(),
            collect_transfer_addr(self.tw_addr),
            self.pt_filter_lib.toPlainText(),
            self.cb_outside.isChecked(),
            self.signal_filter,
        ))
        # 启动线程
        this_thread = getattr(self, this_thread_name)
        this_thread.start(QThread.HighestPriority)

    def on_btn_translate_clicked(self):
        this_thread_name = self.bind_thread_name
        if self.thread_is_running(this_thread_name):
            return
        self.txt_translate_state.setText("")
        setattr(self, this_thread_name, FunctionalThread(
            translate_func,
            self.pt_input.toPlainText(),
            self.pt_output.toPlainText(),
            self.pt_sheet.toPlainText(),
            self.sb_row_from.value(),
            self.sb_row_to.value(),
            collect_transfer_addr(self.tw_addr),
            self.pt_translate_lib.toPlainText(),
            self.cb_other.isChecked(),
            self.signal_translate,
        ))
        # 启动线程
        this_thread = getattr(self, this_thread_name)
        this_thread.start(QThread.HighestPriority)

    def on_btn_count_clicked(self):
        this_thread_name = self.bind_thread_name
        if self.thread_is_running(this_thread_name):
            return
        self.txt_count_state.setText("")
        setattr(self, this_thread_name, FunctionalThread(
            count_func,
            self.pt_input.toPlainText(),
            self.pt_output.toPlainText(),
            self.pt_sheet.toPlainText(),
            self.sb_row_from.value(),
            self.sb_row_to.value(),
            collect_statistic_item(self.tw_statistic),
            self.sb_count_year.value(),
            collect_count_addr(self.tw_addr),
            self.count_mode,
            self.signal_count,
        ))
        # 启动线程
        this_thread = getattr(self, this_thread_name)
        this_thread.start(QThread.HighestPriority)

    def on_btn_bind_name_dept_clicked(self):
        this_thread_name = self.bind_thread_name
        if self.thread_is_running(this_thread_name):
            return
        # 清除上次任务的记录
        self.text_name_dept.setText("")
        # 加载线程
        setattr(self, this_thread_name, FunctionalThread(
            bind_name_dept,
            self.pt_input.toPlainText(),
            self.pt_output.toPlainText(),
            self.pt_sheet.toPlainText(),
            self.sb_row_from.value(),
            self.sb_row_to.value(),
            collect_transfer_addr(self.tw_addr),
            self.signal_bind_dept,
        ))
        # 启动线程
        this_thread = getattr(self, this_thread_name)
        this_thread.start(QThread.HighestPriority)

    # 子线程打印状态
    def on_signal_first(self, msg):
        self.txt_first_state.setText(msg)

    def on_signal_filter(self, msg):
        self.txt_filter_state.setText(msg)

    def on_signal_translate(self, msg):
        self.txt_translate_state.setText(msg)

    def on_signal_count(self, msg):
        self.txt_count_state.setText(msg)

    def on_signal_bind_fullname(self, msg):
        self.txt_bind_fullname_state.setText(msg)

    def on_signal_bind_dept(self, msg):
        self.text_name_dept.setText(msg)

    # 统计模块切换统计模式
    def on_rb_count_author_clicked(self):
        self.count_mode = "author"
    
    def on_rb_count_college_clicked(self):
        self.count_mode = "college"

    # 切换标签页时自动生成输出文件名
    def on_tab_functional_current_changed(self):
        file_path = self.pt_input.toPlainText()
        if file_path != "":
            self.pt_output.setPlainText(file_path_add_sub(file_path, self.tab_functional.tabText(self.tab_functional.currentIndex())))

if __name__ == "__main__":
    app = QApplication(sys.argv)
    #初始化
    main_window = QMainWindow()
    # 导入UI，设置窗口大小和位置
    ui = MyMainUi(main_window)
    #将窗口控件显示在屏幕上
    main_window.show()
    # setup stylesheet
    #apply_stylesheet(app, theme='light_amber.xml')
    #程序运行，sys.exit方法确保程序完整退出。
    sys.exit(app.exec_())